#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class Solution {
public:
    int maxDistance(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        queue<pair<int, int>> as;
        vector<vector<int>> aq(m, vector<int>(n, -1));
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == 1)
                {
                    as.push({ i,j });
                    aq[i][j] = 0;
                }
            }
        }
        int dx[4] = { 0,0,1,-1 };
        int dy[4] = { 1,-1,0,0 };
        int ret = -1;
        while (as.size())
        {
            auto [a, b] = as.front();
            as.pop();
            for (int i = 0; i < 4; i++)
            {
                int x = a + dx[i];
                int y = b + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n && aq[x][y] == -1)
                {
                    aq[x][y] = aq[a][b] + 1;
                    as.push({ x,y });
                    ret = max(ret, aq[x][y]);
                }
            }
        }

        return ret;
    }
};